import { create } from "zustand";
import * as SecurityStore from "expo-secure-store";
import { persist, createJSONStorage } from "zustand/middleware";
import { UserProfileType } from "@/types/user-profile";

interface UserProfileState {
  state: {
    currentUser: UserProfileType;
  };
  actions: {
    setCurrentUserProfile: (profile: UserProfileType) => void;
  };
}

const UserProfileStateStore = create<UserProfileState>()(
  persist(
    (set, get) => ({
      state: {
        currentUser: {
          avatar: "",
          birthday: "",
          email: "",
          gender: 0,
          id: "",
          mobile: "",
          nickname: "",
          region: "",
          signature: "",
          createTime: 0,
          updateTime: 0,
          uuid: "",
        },
      },
      actions: {
        setCurrentUserProfile(profile: UserProfileType): void {
          set((state) => ({
            state: {
              ...state.state,
              currentUser: profile,
            },
          }));
        },
      },
    }),
    {
      name: "user-profile-storage",
      storage: createJSONStorage(() => ({
        getItem: async (name) => {
          const value = await SecurityStore.getItemAsync(name);
          return value ? JSON.parse(value) : null;
        },
        setItem: async (name, value) => {
          await SecurityStore.setItemAsync(name, JSON.stringify(value));
        },
        removeItem: async (name) => {
          await SecurityStore.deleteItemAsync(name);
        },
      })),
    }
  )
);

export default UserProfileStateStore;
